package com.wanmait.recruit.shiro;

import com.wanmait.recruit.pojo.Admin;
import com.wanmait.recruit.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

public class DbRealm extends AuthorizingRealm {
    @Resource
    private AdminService adminService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Admin admin = (Admin)principals.getPrimaryPrincipal();
        Set<String> roles = new HashSet<>();
        admin.getRoles().forEach(role -> roles.add(role.getName()));
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.setRoles(roles);
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userName = (String)authenticationToken.getPrincipal();
        Admin admin = adminService.findAdminByName(userName);
        if(admin==null) return null;
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(admin,admin.getPassword(),this.getClass().getName());
        return authenticationInfo;
    }
    //清空缓存  比如修改权限后 可以通过控制器调用该方法
    public void clearCache(){
        PrincipalCollection principalCollection = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principalCollection);
    }
}
